#include"com.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include<cstring>
#include<fcntl.h>
#include<unistd.h>


int main()
{
    //1、创建命名管道
    umask(0);
    int n = mkfifo(fifoname.c_str(),mode);
    if(n !=0)
    {
        cout<<"errno:"<<errno<<":"<<strerror(errno)<<endl;
        return 1;
    }
    cout<<"creat fifo file success"<<endl;

    //2、服务器端打开管道
    int rfd = open(fifoname.c_str(),O_RDONLY);
    cout<<rfd<<endl;
    //unlink(fifoname.c_str());
    if(rfd == -1)
    {
        cout<<"errno:"<<errno<<":"<<strerror(errno)<<endl;
        return 2;
    }
    cout<<"open fifo file success , can start ipc"<<endl;

    //3、正常通信
    char buffer[NUM];
    while(1)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd,buffer,sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = 0;
            cout<<"client#"<<buffer<<endl;
        }
        else if( n == 0)//当客户关闭管道文件的fd时，read返回0
        {
            cout<<"client quit , me too"<<endl;
            break;
        }
        else
        {
            cout<<"errno:"<<errno<<":"<<strerror(errno)<<endl;
            break;
        }
    }

    close(rfd);
    unlink(fifoname.c_str());


    return 0;
}